import Vue from 'vue'
import Vuex from 'vuex'
import { loadCompanyInfo, loadProductCategory } from './mutation-types'
import api from '../api'
import { htmlDecodeByRegExp } from '../assets/js/utils'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    companyInfo: {
      id: 0,
      companyName: '企业站DEMO',
      tel: '138********',
      address: '广东省深圳市南山区',
      contact: '江**',
      mobile: '12345644564',
      zipCode: '518000',
      email: '410958040@qq.com',
      QQ: '',
      QRCode: '',
      desc: '',
      content: '',
      copyRight: 'MIT Licensed | Copyright © 2019-present 江学美'
    },
    categoryList: []
  },
  getters: {
    htmlContent(state) {
      return htmlDecodeByRegExp(state.companyInfo.content)
    }
  },
  mutations: {
    [loadCompanyInfo](state, payload) {
      state.companyInfo = Object.assign({}, payload.siteInfo)
    },
    [loadProductCategory](state, payload) {
      state.categoryList = [...payload.cates]
    }
  },
  actions: {
    [loadCompanyInfo](context) { // 加载企业站的信息存储在state中
      api.siteinfo().then(res => {
        if (res.data.errorCode === 0) {
          context.commit({
            type: loadCompanyInfo,
            siteInfo: res.data.data
          })
        }
      })
    },
    [loadProductCategory]({ commit }) { // 加载产品分类列表
      api.productcate().then(res => {
        if (res.data.errorCode === 0) {
          commit({
            type: loadProductCategory,
            cates: res.data.data
          })
        }
      })
    }
  }
})

export default store
